package com.stockz.equity.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.stereotype.Repository;

import com.stockz.equity.model.Configuration;

@Repository
public class ConfigurationDaoImpl implements ConfigurationDao {

	@Autowired private JpaTemplate jpaTemplate;
	
	@Override
	public Configuration getByKey(String key) {
		return jpaTemplate.find(Configuration.class, key);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void persist(final Configuration configuration) {
		jpaTemplate.execute(new JpaCallback(){
			@Override
			public Object doInJpa(EntityManager em)
					throws PersistenceException {
					em.getTransaction().begin();
					em.merge(configuration);
					em.getTransaction().commit();
				return null;
			}
		});
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Configuration> getAllConfiguration(){
		return jpaTemplate.find("select c from Configuration c");
	}
	
	public void setJpaTemplate(JpaTemplate jpaTemplate) {
		this.jpaTemplate = jpaTemplate;
	}

}
